#include "databasehandler.h"

DatabaseHandler::DatabaseHandler(QObject *parent) : QObject(parent)
{
    // 构造函数初始化
}

DatabaseHandler::~DatabaseHandler()
{
    // 析构时关闭数据库连接
    if (m_db.isOpen()) {
        m_db.close();
    }
}

bool DatabaseHandler::initDatabase(const QString &dbPath)
{
    // 检查数据库文件是否存在
    bool isNewDB = !QFile::exists(dbPath);

    // 设置ODBC连接字符串
    QString dsn = QString("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%1").arg(dbPath);

    // 配置数据库连接
    m_db = QSqlDatabase::addDatabase("QODBC", "ContactManagerConnection");
    m_db.setDatabaseName(dsn);

    // 打开数据库连接
    if (!m_db.open()) {
        m_lastError = m_db.lastError().text();
        qDebug() << "Failed to open database:" << m_lastError;
        return false;
    }

    // 如果是新数据库，创建表结构
    if (1) {
        if (!createTables()) {
            m_db.close();
            QFile::remove(dbPath); // 删除创建失败的数据库文件
            return false;
        }
    }

    return true;
}

bool DatabaseHandler::createTables()
{
    QSqlQuery query(m_db);

    // 创建联系人表
    QString sql = "CREATE TABLE Contacts ("
                  "ID AUTOINCREMENT PRIMARY KEY, "
                  "Name TEXT NOT NULL, "
                  "Phone TEXT, "
                  "Email TEXT, "
                  "Address TEXT)";

    if (!query.exec(sql)) {
        m_lastError = query.lastError().text();
        qDebug() << "Failed to create Contacts table:" << m_lastError;
        return false;
    }

    return true;
}

bool DatabaseHandler::addContact(const QString &name, const QString &phone,
                               const QString &email, const QString &address)
{
    QSqlQuery query(m_db);
    query.prepare("INSERT INTO Contacts (Name, Phone, Email, Address) "
                  "VALUES (:name, :phone, :email, :address)");
    query.bindValue(":name", name);
    query.bindValue(":phone", phone);
    query.bindValue(":email", email);
    query.bindValue(":address", address);

    if (!query.exec()) {
        m_lastError = query.lastError().text();
        return false;
    }

    return true;
}

bool DatabaseHandler::updateContact(int id, const QString &name, const QString &phone,
                                  const QString &email, const QString &address)
{
    QSqlQuery query(m_db);
    query.prepare("UPDATE Contacts SET "
                  "Name = :name, "
                  "Phone = :phone, "
                  "Email = :email, "
                  "Address = :address "
                  "WHERE ID = :id");
    query.bindValue(":name", name);
    query.bindValue(":phone", phone);
    query.bindValue(":email", email);
    query.bindValue(":address", address);
    query.bindValue(":id", id);

    if (!query.exec()) {
        m_lastError = query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

bool DatabaseHandler::deleteContact(int id)
{
    QSqlQuery query(m_db);
    query.prepare("DELETE FROM Contacts WHERE ID = :id");
    query.bindValue(":id", id);

    if (!query.exec()) {
        m_lastError = query.lastError().text();
        return false;
    }

    return query.numRowsAffected() > 0;
}

QList<QList<QVariant>> DatabaseHandler::getAllContacts()
{
    QList<QList<QVariant>> contacts;
    QSqlQuery query("SELECT ID, Name, Phone, Email, Address FROM Contacts ORDER BY Name", m_db);

    while (query.next()) {
        QList<QVariant> contact;
        contact << query.value("ID")
                << query.value("Name")
                << query.value("Phone")
                << query.value("Email")
                << query.value("Address");
        contacts.append(contact);
    }

    return contacts;
}

QList<QVariant> DatabaseHandler::getContactById(int id)
{
    QSqlQuery query(m_db);
    query.prepare("SELECT ID, Name, Phone, Email, Address FROM Contacts WHERE ID = :id");
    query.bindValue(":id", id);

    if (!query.exec() || !query.next()) {
        m_lastError = query.lastError().text();
        return QList<QVariant>();
    }

    QList<QVariant> contact;
    contact << query.value("ID")
            << query.value("Name")
            << query.value("Phone")
            << query.value("Email")
            << query.value("Address");

    return contact;
}

QString DatabaseHandler::lastError() const
{
    return m_lastError;
}
